import { useNavigate, useSearchParams } from "react-router-dom";
import styles from "./index.module.css";
import {
  Avatar,
  Button,
  Cascader,
  Form,
  Input,
  NavBar,
  Toast,
} from "antd-mobile";
import mapData from "../../../json/map";
import { useEffect, useState } from "react";
import {
  AddCircleOutline,
  CloseCircleOutline,
  EditSOutline,
  MinusCircleOutline,
} from "antd-mobile-icons";
import Pouops from "../../../component/pouop";
import request from "../../../axios";
const Edit = () => {
  const navigate = useNavigate();
  const [searParams] = useSearchParams();
  const [form]: any = Form.useForm();
  const [formIs,setFormIs] = useState<boolean>(false);

  const type: string = searParams.get("type") || "";

  const [visible, setVisible] = useState<boolean>(false);
  const [visible1, setVisible1] = useState<boolean>(false);
  const [len, setLen] = useState<number>(1);

  const [headerList, setHeader] = useState<any[]>([]);

  const [salesList, setSalesList] = useState<any[]>([]);

  const handleIconClick = (ind: number) => {
    const newData = JSON.parse(JSON.stringify(salesList));
    const now = newData.find((item: any) => item.id === ind);
    now.checked = false;
    setSalesList(newData);
  };

  const handleSets = (id: any, ids: string, codes: string) => {
    const newData = JSON.parse(JSON.stringify(headerList));
    const nowId = newData.find((item: any) => item.id == id);
    if (nowId) {
      nowId.checked = true;
    }

    const newDatas = JSON.parse(JSON.stringify(salesList));
    const nowIds = newDatas.filter((item: any) => (ids || '').includes(item.id));
    nowIds.forEach((item: any) => {
      item.checked = true;
    });

    setLen(codes.split(",").length);
    codes.split(",").forEach((item: any, ind: number) => {
      form.setFieldValue(`companyName${ind + 1}`, item);
    });
    setHeader(newData);
    setSalesList(newDatas);
  };

  const setFormVal = () => {
    const obj: any = JSON.parse(searParams.get("obj") || "{}");
    const address: string[] = [];
    if (obj.province) {
      address.push(obj.province);
    }
    if (obj.municipal) {
      address.push(obj.municipal);
    }
    if (obj.district) {
      address.push(obj.district);
    }

    // 回显员工和店长
    handleSets(obj?.managerId, obj?.managerMerber, obj?.deviceCode);
    form.setFieldsValue({
      ...obj,
      address,
    });
  };

  const getUserList = async () => {
    try {
      const { data } = await request.get("/user/list", {
        pageNo: 1,
        pageSize: 999,
      });

      if (data) {
        const records = data?.records || [];
        setHeader(records);
        setSalesList(records);
        setFormIs(true)
      }
    } catch (error) {}
  };

  const handleSubmit = async (val: any) => {
    const regex = /\d+$/,
      codeList = [];
    for (let i in val) {
      if (regex.test(i)) {
        codeList.push(val[i]);
      }
    }
    const id: string|number = type === 'edit' ? JSON.parse(searParams.get('obj') || '{}')?.id : null
    const url: string = type === 'edit' ? '/store/update' : '/store/create';
    const subObj: any = {
      id,
      code: val?.code,
      name: val?.name,
      province: val?.address?.[0] || null,
      municipal: val?.address?.[1] || null,
      district: val?.address?.[2] || null,
      addressDetail: val?.addressDetail,
      deviceCode: codeList?.length ? codeList.join(",") : null,
      managerId: headerList?.find((item: any) => item?.checked)?.id || null,
      managerName: headerList?.find((item: any) => item?.checked)?.name || null,
      managerMerber:
        salesList
          ?.filter((item: any) => item?.checked)
          ?.map((item: any) => item?.id)
          .join(",") || null,
    };
    try {
      await request.post(url, subObj);
      Toast.show("提交成功");
      navigate(-1);
    } catch (error) {}
  };

  useEffect(() => {
    getUserList();
  }, []);

  useEffect(() => { 
    if(type === "edit") {
        setFormVal();
    }
  }, [formIs]);

  return (
    <div className={styles.content}>
      <NavBar
        onBack={() => {
          navigate(-1);
        }}
        style={{ padding: "8px 20px" }}
      >
        {type === "add" ? "添加门店" : "编辑门店"}
      </NavBar>
      <Form
        layout="horizontal"
        mode="card"
        form={form}
        onFinish={async (val) => {
          await handleSubmit(val);
        }}
        footer={
          <div
            style={{
              width: "100%",
              display: "flex",
              justifyContent: "space-around",
              alignItems: "center",
              height: "60px",
            }}
          >
            <Button
              block
              type="submit"
              color="primary"
              size="large"
              className={styles.subbtn}
            >
              确认{type === "add" ? "新增" : "编辑"}
            </Button>
          </div>
        }
      >
        <Form.Item name="code" label="门店编码" className={styles.input_title}>
          <Input
            onChange={console.log}
            placeholder="请输入门店编码"
            disabled={true}
          />
        </Form.Item>
        <Form.Item name="name" label="门店名称" className={styles.input_title}>
          <Input onChange={console.log} placeholder="请输入门店名称" />
        </Form.Item>
        <Form.Item
          name="address"
          label="位置信息"
          className={styles.input_title}
          trigger="onConfirm"
          onClick={(e, datePickerRef: any) => {
            datePickerRef.current?.open();
          }}
        >
          <Cascader options={mapData}>
            {() =>
              form.getFieldValue("address") ? (
                form.getFieldValue("address")
              ) : (
                <span className={styles.default}>请完善位置信息</span>
              )
            }
          </Cascader>
        </Form.Item>
        <Form.Item
          name="addressDetail"
          label="详细地址"
          className={styles.input_title}
        >
          <Input onChange={console.log} placeholder="请输入详细地址" />
        </Form.Item>
        {new Array(len).fill("").map((_: any, ind: number) => {
          return (
            <Form.Item
              name={`companyName${ind + 1}`}
              label={`门店设备${ind + 1}`}
              className={styles.input_title}
              extra={
                ind === 0 ? (
                  <AddCircleOutline
                    fontSize={25}
                    onClick={() => setLen(len + 1)}
                  />
                ) : (
                  <MinusCircleOutline
                    fontSize={25}
                    onClick={() => {
                      if (len !== 1) {
                        setLen(len - 1);
                      }
                    }}
                  />
                )
              }
            >
              <Input onChange={console.log} placeholder="请输入门店设备编码" />
            </Form.Item>
          );
        })}
        <Form.Item
          name="shopName"
          label="门店店长"
          className={styles.input_title}
          onClick={() => {
            setVisible(true);
          }}
        >
          {headerList?.some((item: any) => item?.checked) ? (
            headerList.find((item: any) => item?.checked).name
          ) : (
            <span className={styles.default}>请选择门店店长</span>
          )}
        </Form.Item>
        <Pouops
          data={headerList}
          setData={setHeader}
          value={visible}
          setValue={setVisible}
          type="radio"
        />
        <Form.Item
          name="shopNames"
          label="门店店员"
          className={styles.input_title}
        >
          <span className={styles.edit}>
            <EditSOutline />
            <span onClick={() => setVisible1(true)}>编辑</span>
          </span>
        </Form.Item>
        <Pouops
          data={salesList}
          setData={setSalesList}
          value={visible1}
          setValue={setVisible1}
          type="checkbox"
        />
        <div className={styles.salesList}>
          {salesList
            .filter((item: any) => item?.checked)
            .map((item: any) => {
              return (
                <div className={styles.salesItem}>
                  <CloseCircleOutline
                    className={styles.icon}
                    onClick={() => handleIconClick(item.id)}
                  />
                  <Avatar
                    src=""
                    style={{ "--size": "48px", borderRadius: "50%" }}
                  />
                  <span>{item.name}</span>
                </div>
              );
            })}
        </div>
      </Form>
    </div>
  );
};

export default Edit;
